<?php

/**
 * @version		$Id: view.html.php 21367 2011-05-18 12:29:19Z chdemko $
 * @copyright	Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.view');


class PromotionsViewRedemptions extends JViewLegacy
{
	protected $state = null;
	protected $item = null;
	protected $items = null;
    protected $params;

	function display($tpl = null){   

        $app = &JFactory::getApplication();   
		$session_vipcard =& JFactory::getSession();
		$session_vipcard_id =  $session_vipcard->getId();
        
        switch($this->getLayout()){
            case 'addtocart':
                $this->displayAddtocart($tpl);
                exit();
                break;
            
            case 'details':
                $this->displayDetails($tpl);    
                break;
            
            case 'list':
                $this->displayList($tpl);    
                return false; break;
            
            case 'shoppingcart':
                $this->displayShoppingcart($tpl);    
                return false;
                break;
        }

        /***** Init Cookie *****/
        $cookieName = md5($session_vipcard_id);
        if(isset($_COOKIE[$cookieName])){
            $_SESSION['shoppingCart'] = trim($_COOKIE[$cookieName], ',');
        }
        else {
            $config = JFactory::getConfig();
            $cookie_domain = $config->get('cookie_domain', '');
            $cookie_path = $config->get('cookie_path', '/');
            jimport('joomla.utilities.utility');
            setcookie($cookieName, '', time() + 2 * 86400, $cookie_path, $cookie_domain);    
        }
        
        /**** Init varibales ****/
        $db = JFactory::getDbo();
        $user = JFactory::getUser();
        
        if($user->id != 0)
        	$userPoint =WrdHelper::getPointsofUser($user->id);   
        else
        	$userPoint = 0;
        
        $_SESSION[$user->id.'p'] = $userPoint;
        $items		= $this->get('ItemsShop');
        $category_detail = $this->getCatDetail();
        
		// Check for errors.
		if (count($errors = $this->get('Errors'))) {
			JError::raiseWarning(500, implode("\n", $errors));
			return false;
		}
        
		$total					= & $this->get( 'Total');
		$pagination 			= & $this->get( 'Pagination' );
		
		$this->assignRef('user', $user);
        $this->assignRef('items', $items);
        $this->assignRef('category_detail', $category_detail);
        $this->assignRef('userPoint', $userPoint);
        $this->assignRef('pagination',	$pagination);
        $this->_prepareDocument();
		parent::display($tpl);
	}
    
    /*
     * View Promotion Details
     */
    function displayList($tpl = null){
        $db = JFactory::getDbo();
        $models = PointProvider::latestRedemptions($db);
        
        $this->assignRef('models', $models);
        $this->layout = 'list';        
        parent::display($tpl);
    }
    
    private function checkCookieShoppingCart(){
        $listRatedArticles = array();
        if (isset($_SESSION['shoppingCart']))
        {
            $ratedArticles = $_SESSION['shoppingCart'];
            $listRatedArticles = explode(',', $ratedArticles);
        }
        return in_array($this->itemId, $listRatedArticles);
    }
    
    /*
     * Confirm Shopping cart
     */
    function displayShoppingcart($tpl = null){
        //echo 123;exit;
        /*** Init ***/
    	$app = JFactory::getApplication('site');
        $session_vipcard =& JFactory::getSession();
		$session_vipcard_id =  $session_vipcard->getId();
		
        $db = JFactory::getDbo();
        $user = JFactory::getUser();
        $items = $_COOKIE[md5($session_vipcard_id)];
		
		$config = new JConfig;
		$serect = md5($config->secret);
		$cart = base64_decode($items);
		$cart = str_replace($serect, '', $cart);
		$cart = base64_decode($cart);
		
		
        $items = json_decode($cart);

    	$user_profile = WrdHelper::getUserProfile($user->id);
    
        if(count($items) <= 0){
		
        	$app->redirect('index.php?option=com_promotions&view=redemptions&Itemid=175');
        }
        
        $params = array();
		//echo $_POST['pick_up_at'];exit;
        if(isset($_POST['pick_up_at'])){
            
			$params['save'] = true;
            //get list point of user
            $arr_tmp_points =  array();
            $vercode = WrdHelper::random_letters();
            $this->assignRef('redemption_code', $vercode);
          
            if($user->id != 0){
				
				$userPoint = WrdHelper::getPointsofUser($user->id);
				
            	$points    = PointProvider::getPointOfUser($db, array('userId'=>$user->id));
            	 
				$total_point = 0;
            	//calculate point
            	foreach ($items as $item){
            		
            		if($item->type == 1)
            			$total_point =  $total_point +  ($item->qty * $item->point);
            		else
            			$total_point =  $total_point +  ($item->qty * $item->pointx);
            	}
            	
            	if($total_point > $userPoint){
            		// cheat
            		$app->redirect('index.php#login');
            	}
				
            $outlet = WrdHelper::getOutlet($_POST['pick_up_at']);
			
            $user_profile->point_redemption = $total_point;
			$user_profile->point_after_exchange = ($user_profile->p_o_u - $user_profile->point_redemption);
			
			//echo "<pre>";print_r($user_profile);exit;
			
				$point_remain = $total_point;
				foreach ($points as $raw=>$point){
					
					$point->point = intval($point->point);
					if(($total_point - $point->point) > 0)
					
						$arr_tmp_points[$raw]['point'] = - $point->point;
					else 
						$arr_tmp_points[$raw]['point'] = - $total_point;
					
					$arr_tmp_points[$raw]['user_id'] = $user->id ;
            		$arr_tmp_points[$raw]['redemption_id'] = $vercode;
            		$arr_tmp_points[$raw]['transaction'] = $point->transaction;
            		$arr_tmp_points[$raw]['type'] = 9;
            		$arr_tmp_points[$raw]['expire'] = '0000-00-00 00:00:00' ;
            		$arr_tmp_points[$raw]['des'] = 'Redemption-'.$vercode;
            		$arr_tmp_points[$raw]['created_id'] = $user->id ;
            		$arr_tmp_points[$raw]['created_date'] = date('Y-m-d H:m:s') ;
            		$arr_tmp_points[$raw]['modify_id'] = '';
            		$arr_tmp_points[$raw]['modify_date'] = '';
            		$arr_tmp_points[$raw]['flagConvert'] = '1';
            		
            		$total_point = $total_point - $point->point;
            		if($total_point < 0)
            			break;
            	}
            	
            	//inser point table
            	foreach ($arr_tmp_points as $arr_tmp_point){
				
            		$point_obj = new stdClass();
            		$point_obj->id = null;
            		$point_obj->point = $arr_tmp_point['point'];
            		$point_obj->user_id = $arr_tmp_point['user_id'];
            		$point_obj->redemption_id = $arr_tmp_point['redemption_id']; 
            		$point_obj->transaction = $arr_tmp_point['transaction']; 
            		$point_obj->type = $arr_tmp_point['type'];
            		$point_obj->expire = $arr_tmp_point['expire']; 
            		$point_obj->des = $arr_tmp_point['des'];
            		$point_obj->created_id = $arr_tmp_point['created_id'];
            		$point_obj->created_date = $arr_tmp_point['created_date'];
            		$point_obj->modify_id = $arr_tmp_point['modify_id'];
            		$point_obj->modify_date = $arr_tmp_point['modify_date'];
            		
            		$db->insertObject('#__wrd_point', $point_obj) ;
            	}
	
            	//insert redemption table
            	if($user_profile->nationality == 249){
				
					$list_items = "<table width='100%' border='1'><tr><th>Thứ tự</th><th>Số lượng</th><th>Tên món quà</th><th>Điểm</th><th>Tiền</th></tr>";
				}
				else {
				
					$list_items = "<table width='100%' border='1'><tr><th>Order</th><th>Quantity</th><th>Product Name</th><th>Point</th><th>Cash</th></tr>";
				}
				
				$count = 0;
				foreach ($items as $item){
            		
					$count++;
            		$product = WrdHelper::getProduct($item->id);
					$productName = unserialize($product->name);
					
					if($user_profile->nationality == 249){
					
						$productName = $productName['vi-VN'];
						$user_profile->pickup_place = $outlet->name_vi;
						$user_profile->pickup_place_address = $outlet->address_vi;
					}
					else {
					
						$productName = $productName['en-GB'];
						$user_profile->pickup_place = $outlet->name;
						$user_profile->pickup_place_address = $outlet->address;
					}
					
					$point_Of_Items = number_format( (($item->type == 1) ? $item->point : $item->pointx) * $item->qty ,0,".",",");
					
					$cash = number_format($item->cash * $item->qty,0,".",",");
					
					$list_items .= "<tr><td>$count</td><td>$item->qty</td><td>$productName</td><td>$point_Of_Items</td><td>$cash</td></tr>";
					
					//check product is voucher
            		$is_voucher = $this->checkVoucher($item->id);
            		if($is_voucher->voucher == 1)
            		{
            			
            			
						for($tmp_qty = 1; $tmp_qty <= $item->qty; $tmp_qty++ ){
            				
            				$source_obj = new stdClass() ;
            				$source_obj->id = null;
            				$source_obj->user_id = $user->id;
            				$source_obj->product_id = $item->id;
            				$source_obj->exchange_date = date("Y-m-d");
            				$source_obj->approved = 0;
            				$source_obj->approved_date = '';
            				$source_obj->code = $vercode;
            				
            				if($item->type == 1){
            					$source_obj->point = $item->point ;
            					$source_obj->cash = 0;
            				}
            				else {
            					$source_obj->point = $item->pointx ;
            					$source_obj->cash = $item->cash;
            				}
            				
            				$source_obj->point_id = 0;
            				$source_obj->status_of_redemption = 0;
            				$source_obj->status_of_redemption_date = '0000-00-00';
            				$source_obj->pick_up_date = '0000-00-00';
            				$source_obj->phone_num = '';
            				$source_obj->created_id = $user->id;
            				$source_obj->quantity = 1 ;
            				$source_obj->pick_up_at = $_POST['pick_up_at'] ;
							$source_obj->requested_outlet = $_POST['pick_up_at'] ;

            				$db->insertObject('#__wrd_redemption', $source_obj) ;
            				$id_redemption = $db->insertid();
            				
            				$redem_report_voucher = new stdClass();
            				$redem_report_voucher->id = null;
            				$redem_report_voucher->outlet_voucher = 0;
            				$redem_report_voucher->outlet_name_use_voucher = '';
            				$redem_report_voucher->member_id =  $user_profile->member_id;
            				$redem_report_voucher->product_id = $item->id;
            				$redem_report_voucher->product_cost = $is_voucher->price;
            				$redem_report_voucher->cost_pricing = $is_voucher->cost_pricing;
            				
            				$redem_report_voucher->date_voucher = '';
            				$redem_report_voucher->code_redemption = $vercode;
            				$redem_report_voucher->code_voucher = '';
            				$redem_report_voucher->status = 0;
            				
            				$db->insertObject('#__wrd_redem_report_voucher', $redem_report_voucher) ;
            				$idrv = $db->insertid();
            				
            				//update idrv to redemtion
            				$tmp_update_idrv = new stdClass();
            				$tmp_update_idrv->id 	= $id_redemption;
            				$tmp_update_idrv->idrv 	= $idrv;
            				$db->updateObject('#__wrd_redemption', $tmp_update_idrv, 'id');
            			}
            			
            		}
            		else{
					
            			$source_obj = new stdClass() ;
            			$source_obj->id = null;
            			$source_obj->user_id = $user->id;
            			$source_obj->product_id = $item->id;
            			$source_obj->exchange_date = date("Y-m-d");
            			$source_obj->approved = 0;
            			$source_obj->approved_date = '';
            			$source_obj->code = $vercode;
            			
            			if($item->type == 1){
            				$source_obj->point = $item->point*$item->qty ;
            				$source_obj->cash = 0;
            			}
            			else {
            				$source_obj->point = $item->pointx*$item->qty;
            				$source_obj->cash = $item->cash*$item->qty;
            			}
            			
            			$source_obj->point_id = 0;
            			$source_obj->status_of_redemption = 0;
            			$source_obj->status_of_redemption_date = '0000-00-00';
            			$source_obj->pick_up_date = '0000-00-00';
            			$source_obj->phone_num = '';
            			$source_obj->created_id = $user->id;
            			$source_obj->quantity = $item->qty ;
            			$source_obj->pick_up_at = $_POST['pick_up_at'] ;
            			$source_obj->requested_outlet = $_POST['pick_up_at'] ;
						
            			$db->insertObject('#__wrd_redemption', $source_obj) ;
						
						
            		}

	            	//update product items
	            	$query = 'SELECT quantity FROM #__wrd_products WHERE id = '.$item->id;

	            	$db->setQuery($query);
	            	$product_obj = $db->loadObject();

	            	$remain = intval($product_obj->quantity) - intval($item->qty);
	            	$query = 'UPDATE #__wrd_products SET quantity = "'.$remain.'" WHERE id = '.$item->id;
	            	$db->setQuery($query);
	            	$db->query();

            	}
            	$list_items .= "</table>";
				
            	// Send email template redemption_notice to user and admin 
            	WrdHelper::sendEmailWhenRedemption($user_profile,$list_items);
            	
            	$point_query = 'SELECT c.name as outlet_name, b.transaction_id as table_transaction, b.outlet,a.* FROM #__wrd_point as a
									left join #__wrd_transaction as b on a.transaction = b.transaction_id
									left join #__wrd_outlets as c on b.outlet = c.code
									where redemption_id = "'.$vercode.'"';
            	$point_obj = $db->setQuery($point_query)->loadObjectList();
            	
            	
            	$voucher_query = 'SELECT b.cost_pricing,a.* FROM #__wrd_redem_report_voucher as a
										LEFT JOIN #__wrd_products as b on a.product_id = b.id
										WHERE code_redemption =  "'.$vercode.'"';
            	$voucher_obj = $db->setQuery($voucher_query)->loadObjectList();
            	
            	foreach ($voucher_obj as $v_obj){
            		foreach ($point_obj as $child_obj){
            			if($child_obj->outlet == '')
            				$child_obj->outlet = 0;
            			if($child_obj->outlet_name == '')
            				$child_obj->outlet_name = 'WMC GROUP';
            			 
            			$child_obj->point = abs($child_obj->point);
            			 
            			$percent = round(($child_obj->point/$point_remain)*100,2);
            			 
            			$rrs_obj = new stdClass();
            			$rrs_obj->id = null;
            			$rrs_obj->rrvid = $v_obj->id;
            			$rrs_obj->outlet = $child_obj->outlet;
            			$rrs_obj->outletName = $child_obj->outlet_name;
            			$rrs_obj->percent = $percent;
            			$rrs_obj->charge_cost = ($percent*$v_obj->cost_pricing)/100;
            			$db->insertObject('#__wrd_rrv_outlet', $rrs_obj) ;
            		}
            	
            	}
            	
            	WrdHelper::updateSummaryPoint($user->id,date('Y'),date('m'));
            	$p_o_u = WrdHelper::updatePointOfUser($user->id,$user_profile->member_id,$user_profile->dob,$user_profile->f_name,$user_profile->l_name);
            	
            	$_SESSION[$user->id.'p'] = $p_o_u;
            	setcookie(md5($session_vipcard_id), '');
				
            }
            else{
            	//request login
            	$app->redirect('index.php#login');
            }
            
        }
        else {
            $params['save'] = false;
            $userPoint = WrdHelper::getPointsofUser($user->id);
        }

        $this->assignRef('userPoint', $userPoint);
        $this->assignRef('items', $items);
        
        $this->assignRef('params', $params);
        $this->_prepareDocument();
        parent::display($tpl);
    }
	
    private function saveRedemption(){
	
        $this->layout = 'saveredemption';
    }
    
    /*
     * Update shopping cart
     */
    function displayAddtocart($tpl = null){
        $result = array();
        $result['success'] = false;
		$result['html'] = '';
        if(isset($_POST['params'])){
            $db = JFactory::getDbo();
            $params = json_decode($_POST['params']);
			
            $result['qty'] 		= ($params->qty);
			$result['point'] 	= ($params->point);
			$result['pointx'] 	= ($params->pointx);
			$result['type'] 	= ($params->type);
            $result['id'] 		= ($params->id);
			$result['qtyTotal'] = ($params->ptotal);
			$result['cash'] 	= ($params->cash);
			
            $qty = PointProvider::checkProductQuantity($db, array('ids'=>$result['id']));
           
            if(!empty($qty)) {

				if( $result['type'] == 1)
				{
					if($qty[0]->point !=  $result['point']){
						$result['debug']['type'] = $qty[0]->type;
						$result['debug']['point'] = $qty[0]->point;
						$result['debug']['pointx'] = $qty[0]->pointx;
						$result['debug']['cash'] = $qty[0]->cash;
						
						$result['refresh'] = false;
						$result = json_encode($result);
						echo "({$result})";
	        			exit;
					}
				}else{
					if($qty[0]->pointx !=  $result['pointx'] || $qty[0]->cash !=  $result['cash']){
						$result['debug']['type'] = $qty[0]->type;
						$result['debug']['point'] = $qty[0]->point;
						$result['debug']['pointx'] = $qty[0]->pointx;
						$result['debug']['cash'] = $qty[0]->cash;
						
						$result['refresh'] = false;
						$result = json_encode($result);
						echo "({$result})";
	        			exit;
					}
				}


                if($qty[0]->quantity < $result['qtyTotal']){
				
                	$lang =& JFactory::getLanguage();
                	$qty[0]->name = unserialize($qty[0]->name);
                	$productname = $qty[0]->name[$lang->getTag()];
                	
                	$errortext = JText::sprintf('WRD_PROMOTION_CURRENT_QUALITY_ERROR',$productname,$qty[0]->quantity,$result['qtyTotal']);
                    $result['html'] = $errortext;
					$result['max'] = $qty[0]->quantity;
					$result['allow'] = $result['qty'] - ($result['qtyTotal'] - $qty[0]->quantity);
                }
                else {
                    $result['success'] = true;
                    $result['qtyTotal'] = $result['qtyTotal'];
                }
            } 
        }
        
		$session_vipcard =& JFactory::getSession();
		$session_vipcard_id =  $session_vipcard->getId();

        $result = json_encode($result);
        echo "({$result})";
        exit;
    }
    
    /*
     * View Promotion Details
     */
    function displayDetails($tpl = null){
    	
    	$app 				= &JFactory::getApplication('site');
    	$session_vipcard 	= &JFactory::getSession();
    	$session_vipcard_id = $session_vipcard->getId();
    	
    	$db = JFactory::getDbo();
    	$user = JFactory::getUser();

		$items = $_COOKIE[md5($session_vipcard_id)];
		
		$config = new JConfig;
		$serect = md5($config->secret);
		$cart = base64_decode($items);
		$cart = str_replace($serect, '', $cart);
		$cart = base64_decode($cart);
		
		
        $items = json_decode($cart);

    	$this->setModel($this->getModel(), true);

        $model = $this->get('itemById');
		$gallery = $this->get('gallery');
		//var_dump($gallery);
		$this->assignRef('cookie_items', $items);
        $this->assignRef('model', $model);
		$this->assignRef('gallery', $gallery);
    }
    
    function getCatDetail(){
    	
    	$cat_id =  JRequest::getInt('id');
    	$cat_obj = new stdClass();
    	
    	if($cat_id == -1){
    		$cat_obj->title = 'NOT KNOWN';
    		
    	}
    	elseif($cat_id == 0){
    		$cat_obj->title = JText::_('WRD_PROMOTION_BROWSE_ALL_THE_GIFTS');
    	}
    	else{
    		$db = JFactory::getDbo();
    		$query = 'SELECT * FROM #__wrd_pcategory WHERE id = '.$cat_id;
    		
    		$db->setQuery($query);
    		$cat_obj = $db->loadObject();
    	}
    	//print_r($cat_obj);

    	return $cat_obj;
    }
    
    function checkVoucher($product_id){
    	if($product_id == 0)
    		return false;
    	
    	$db = &JFactory::getDbo();
    	$query = 'SELECT * FROM #__wrd_products where id = '.$product_id;
    	
    	return $db->setQuery($query)->loadObject();
    }
    
	protected function _prepareDocument()
	{
		$app	= JFactory::getApplication();
		$menus	= $app->getMenu();
		$title	= null;

		$menu = $menus->getActive();

		$title = JText::_('COM_PROMOTION_DEFAULT_PAGE_TITLE');

		$this->document->setTitle($title);

	}
}
